# -*- encoding: utf-8 -*-
"""
File Name: AlarmHandler
Description:
Author : 'lirui'
date: 2024/2/8
Contact: marjey_lee@163.com
Change Activity:
2024/2/8:
"""
import json
import abc
import ll
from ll import TimeFormat
from projects.monitoring.alarm_manager.services.redis_alarm_manager import REDIS_ALARM_MANAGER
from projects.monitoring.alarm_manager.utils.alarm_classification import AlarmClassifier
from projects.monitoring.alarm_manager.utils.alarm_sender import AlarmSender


class AlarmHandler(abc.ABC):
    REDIS_KEY = 'base_problems'

    @staticmethod
    def _format_subscribe_info(msg):
        try:
            data = str(msg['data'], 'UTF8')
            if data.startswith('[') or data.startswith('{'):
                data = json.loads(data)
                return data
        except Exception as e:
            ll.get_logger().warning(f'Load data to json error:{e}')
            return None

    @staticmethod
    @abc.abstractmethod
    def _format_receive_alarm(data):
        """

        """
        pass

    @staticmethod
    def _update_latest_monitoring_time(alarms):
        """

        Args:
            alarms:

        Returns:

        """
        current_time = TimeFormat.get_current_time(format_str="%Y-%m-%d %H:%M:%S")
        for _, alarm in alarms.items():
            alarm.set_latest_monitoring_time(current_time)
        return alarms

    @classmethod
    def handle_subscribe_info(cls, msg):
        data = cls._format_subscribe_info(msg)
        if data is None:
            return
        data = cls._format_receive_alarm(data)
        data = cls._update_latest_monitoring_time(data)
        classifier = AlarmClassifier()
        remind, warning = classifier.classify_problems(data)
        ll.get_logger().info(f'Receive msg {len(data)}, {cls.REDIS_KEY}')
        new_problems, recovery_problems = REDIS_ALARM_MANAGER.refresh_redis_problems(
            warning, redis_key=cls.REDIS_KEY
        )
        new_problems = classifier(new_problems)
        recovery_problems = classifier(recovery_problems)
        AlarmSender.send_alarm(new_problems)
        AlarmSender.send_recovery(recovery_problems)
